package com.oocl.thread;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Map;

import com.oocl.chat.operate.impl.WorkOperateImpl;
import com.oocl.chat.pojo.Message;
import com.oocl.chat.util.MaintainMap;
import com.oocl.chat.util.MapOperate;

public class SocketListener implements Runnable{
	private Socket socket;
	private ObjectInputStream ois;
	private ObjectOutputStream oos;
	private boolean quit = false;
	WorkOperateImpl work = new WorkOperateImpl();

	public SocketListener(Socket socket) throws Exception {
		super();
		this.socket = socket;
		this.ois = new ObjectInputStream(socket.getInputStream());
		this.oos = new ObjectOutputStream(socket.getOutputStream());
	}
	public ObjectInputStream getOis() {
		return ois;
	}
	public ObjectOutputStream getOos() {
		return oos;
	}
	
	public void run() {
		while(!quit){
			try {
				begin();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public void begin() throws ClassNotFoundException, IOException{
		Message message = new Message();
		if((message = (Message)ois.readObject())!= null){
			int type = message.getType();
			switch(type){
			case 0:
				work.chat(message,oos);
				break;
			case 1:
				work.shake(message,oos);
				break;
			case 2:
				work.online(message,oos);
				break;
			case 3:
				work.downline(message,oos);
				quit = true;
				closeFlow();
				break;
			}
			
		}
	}

	private void closeFlow(){
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
